package com.example.translateappjava.Fragment;

import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.READ_MEDIA_IMAGES;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.content.Context;
import android.annotation.SuppressLint;
import android.app.Activity; //  <--- 确保 Activity 被引入
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SearchView;
import android.widget.Toast;
import android.widget.TextView;
import android.Manifest;
import androidx.appcompat.app.AlertDialog;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import com.example.translateappjava.Activity.HomeFragmentActivity.CalculatorActivity;
import com.example.translateappjava.Activity.HomeFragmentActivity.Forum.ForumActivity;
import com.example.translateappjava.Activity.HomeFragmentActivity.RobotActivity;
import com.example.translateappjava.Activity.HomeFragmentActivity.SelectActivity;
import com.example.translateappjava.Activity.MainActivity;
import com.example.translateappjava.Activity.ThemeUtilsActivity;
import com.example.translateappjava.Activity.MineFragmentActivity.SettingsActivity;
import com.example.translateappjava.DataBase.DatabaseHelper;
import com.example.translateappjava.Listener.LoadingProgressListener;
import com.example.translateappjava.R;
import com.example.translateappjava.Activity.HomeFragmentActivity.SearchActivity;
import com.example.translateappjava.Service.AliyunAPI.AliyunAPIHelper;
import com.example.translateappjava.Service.ChatGPT.ChatGptHelper;
import com.example.translateappjava.Service.Doubao.DoubaoVisionHelper;
import com.example.translateappjava.Service.FoodCalories.FoodCaloriesHelper;
import com.example.translateappjava.Service.FoodDetails.FoodDetailsHelper;
import com.example.translateappjava.Service.MedicalAtlas.MedicalAtlasHelper;
import com.example.translateappjava.Utils.ImageCaptureManager;
import com.example.translateappjava.Utils.ImageData;
import com.example.translateappjava.Utils.ImageRecognitionManager;
import com.google.android.material.progressindicator.CircularProgressIndicator;
import com.google.android.material.progressindicator.LinearProgressIndicator;
import java.util.ArrayList;

public class HomeFragment extends Fragment implements
        LoadingProgressListener,
        ChatGptHelper.OnChatGptResponseListener,
        AliyunAPIHelper.AliyunAPIListener,
        MedicalAtlasHelper.MedicalAtlasListener,
        FoodCaloriesHelper.FoodCaloriesListener,
        FoodDetailsHelper.FoodDetailsListener,
        DoubaoVisionHelper.DoubaoVisionListener{

    private static final String TAG = "HomeFragment"; // 日志标签
    private static final int REQUEST_CAMERA_PERMISSION = 100;
    private static final int REQUEST_STORAGE_PERMISSION = 101;

    // UI Components
    private ConstraintLayout constraintLayout;
    // private LinearLayout linearLayout; // 似乎未使用
    // private CircularProgressIndicator circularProgressIndicator; // 似乎未使用
    // private LinearProgressIndicator linearProgressIndicator; // 似乎未使用
    private View loadingOverlayContainer;
    private TextView loadingStatusTextViewOverlay;
    private TextView loadingStepDetailsTextViewOverlay;
    // Managers
    private ImageCaptureManager imageCaptureManager;
    private ImageRecognitionManager imageRecognitionManager;


    @SuppressLint("MissingInflatedId")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        int layoutId = R.layout.fragment_home;
        View rootView = inflater.inflate(layoutId, container, false);

        initViews(rootView);
        initManagers();
        setupEventListeners(rootView);

        if (loadingOverlayContainer != null) {
            loadingOverlayContainer.setVisibility(View.GONE);
        }
        Log.d(TAG, "onCreateView completed. Listener instance: " + this.toString());
        return rootView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }


    private void initViews(View rootView) {
        constraintLayout = rootView.findViewById(R.id.constraintLayout); // 确保这个ID在 fragment_home.xml 中
        loadingOverlayContainer = rootView.findViewById(R.id.loading_overlay_container);
        loadingStatusTextViewOverlay = rootView.findViewById(R.id.loading_status_text_overlay);
        loadingStepDetailsTextViewOverlay = rootView.findViewById(R.id.loading_step_details_text_overlay);

        if (loadingOverlayContainer == null) Log.e(TAG, "loadingOverlayContainer is NULL after findViewById");
        if (loadingStatusTextViewOverlay == null) Log.e(TAG, "loadingStatusTextViewOverlay is NULL after findViewById");
        if (loadingStepDetailsTextViewOverlay == null) Log.e(TAG, "loadingStepDetailsTextViewOverlay is NULL after findViewById");

        Log.d(TAG, "Views initialized");
    }

    private void initManagers() {
        imageCaptureManager = new ImageCaptureManager(this);
        imageRecognitionManager = new ImageRecognitionManager(this, getActivity());
        imageRecognitionManager.setRecognitionCompleteListener(this::onRecognitionComplete);
        // 关键点：将 HomeFragment 自身 (this) 作为 LoadingProgressListener 传递给 imageRecognitionManager
        // ImageRecognitionManager 内部会再将此监听器传递给 ImageUploader 和 DiabetesFoodAdvisor
        imageRecognitionManager.setLoadingProgressListener(this);
        Log.d(TAG, "Managers initialized. Set HomeFragment as LoadingProgressListener for ImageRecognitionManager.");
    }

    private void setupEventListeners(View rootView) {
        ImageView imageViewShot = rootView.findViewById(R.id.imageViewShot);
        SearchView searchViewSearch = rootView.findViewById(R.id.imageViewSearch);
        ImageButton caculator = rootView.findViewById(R.id.calculator);
        ImageView imageViewRobot = rootView.findViewById(R.id.imageView5);
        ImageButton select_type = rootView.findViewById(R.id.select_type);
        ImageView imageView = rootView.findViewById(R.id.imageView6);

        if (select_type != null) {
            select_type.setOnClickListener(v -> {
                Intent intent = new Intent(getActivity(), SelectActivity.class);
                startActivity(intent);
            });
        }

        if (imageViewRobot != null) {
            imageViewRobot.setOnClickListener(v -> {
                Intent intent = new Intent(getActivity(), RobotActivity.class);
                startActivity(intent);
            });
        }

        if (searchViewSearch != null) {
            searchViewSearch.setOnClickListener(v -> {
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                startActivity(intent);
            });

            searchViewSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    Intent intent = new Intent(getActivity(), SearchActivity.class);
                    intent.putExtra("query", query);
                    startActivity(intent);
                    DatabaseHelper databaseHelper = new DatabaseHelper(getActivity());
                    databaseHelper.insertData(query);
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    return false;
                }
            });
        }

        if (caculator != null) {
            caculator.setOnClickListener(v -> {
                Intent intent = new Intent(getActivity(), CalculatorActivity.class);
                startActivity(intent);
            });
        }

        if (imageViewShot != null) {
            imageViewShot.setOnClickListener(v -> showChooseImageDialog());
        }

        if (imageView != null) {
            imageView.setOnClickListener(v -> {
                try {
                    Intent intent = new Intent(getActivity(), ForumActivity.class);
                    startActivity(intent);
                    if (getActivity() != null) {
                        getActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                    }
                } catch (Exception e) {
                    Log.e(TAG, "跳转论坛失败", e);
                    Toast.makeText(getActivity(), "暂时无法进入论坛，请稍后重试", Toast.LENGTH_SHORT).show();
                }
            });
        }
        Log.d(TAG, "Event listeners set up");
    }

    private void showChooseImageDialog() {
        if (getContext() == null) return; // 避免Fragment未附加时操作
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_choose_image, null);
        builder.setView(dialogView);
        AlertDialog dialog = builder.create();
        dialog.show();

        Button btnCamera = dialogView.findViewById(R.id.btnCamera);
        btnCamera.setOnClickListener(v -> {
            if (getActivity() == null) return;
            if (ContextCompat.checkSelfPermission(requireContext(), CAMERA) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(), new String[]{CAMERA}, REQUEST_CAMERA_PERMISSION);
            } else {
                imageCaptureManager.launchCamera();
            }
            dialog.dismiss();
        });

        Button btnGallery = dialogView.findViewById(R.id.btnGallery);
        btnGallery.setOnClickListener(v -> {
            if (getActivity() == null) return;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                if (ContextCompat.checkSelfPermission(requireContext(), READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(getActivity(), new String[]{READ_MEDIA_IMAGES}, REQUEST_STORAGE_PERMISSION);
                } else {
                    imageCaptureManager.launchGallery();
                }
            } else {
                if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE_PERMISSION);
                } else {
                    imageCaptureManager.launchGallery();
                }
            }
            dialog.dismiss();
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (getActivity() == null) return;
        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                imageCaptureManager.launchCamera();
            } else {
                Toast.makeText(getActivity(), "需要相机权限以拍摄照片", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == REQUEST_STORAGE_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                imageCaptureManager.launchGallery();
            } else {
                Toast.makeText(getActivity(), "需要存储权限以访问图库", Toast.LENGTH_SHORT).show();
            }
        }
    }

    public void onImageCaptured(Bitmap bitmap) {
        Log.d(TAG, "onImageCaptured called. Starting processing.");
        onProcessingStart("正在准备图片...");
        if (imageRecognitionManager != null) {
            imageRecognitionManager.processImage(bitmap);
        } else {
            Log.e(TAG, "imageRecognitionManager is null in onImageCaptured");
            onProcessingError("内部错误，无法处理图片");
        }
    }

    private void onRecognitionComplete(ArrayList<ImageData> imageDataList) {
        Log.d(TAG, "onRecognitionComplete called. Image recognition finished. Count: " + imageDataList.size());
        // 注意：通常，图片识别完成后，会紧接着进行AI分析（如 DiabetesFoodAdvisor），
        // AI分析完成后，DiabetesFoodAdvisor的finalizeProcessing会调用onProcessingComplete。
        // 所以这里通常不需要直接调用 onProcessingComplete()，除非图片识别本身就是最后一步。
        // 如果 imageDataList 为空或没有有效项，DiabetesFoodAdvisor 应该会处理这种情况并最终调用 onProcessingComplete。
    }

    // --- LoadingProgressListener 实现 ---
    @Override
    public void onProcessingStart(String initialMessage) {
        Activity activity = getActivity();
        if (activity == null) {
            Log.w(TAG, "onProcessingStart: Fragment not attached to an activity.");
            return;
        }
        activity.runOnUiThread(() -> {
            Log.d(TAG, "onProcessingStart (UI Thread): " + initialMessage);
            if (loadingOverlayContainer != null) {
                if (loadingStatusTextViewOverlay != null) {
                    loadingStatusTextViewOverlay.setText(initialMessage);
                } else {
                    Log.e(TAG, "onProcessingStart: loadingStatusTextViewOverlay is null!");
                }
                if (loadingStepDetailsTextViewOverlay != null) {
                    loadingStepDetailsTextViewOverlay.setText(""); // 清空详情
                    loadingStepDetailsTextViewOverlay.setVisibility(View.GONE);
                } else {
                    Log.e(TAG, "onProcessingStart: loadingStepDetailsTextViewOverlay is null!");
                }
                loadingOverlayContainer.setVisibility(View.VISIBLE);
                Log.d(TAG, "onProcessingStart: loadingOverlayContainer set to VISIBLE.");
            } else {
                Log.e(TAG, "onProcessingStart: loadingOverlayContainer is null!");
            }
        });
    }

    @Override
    public void onProgressUpdate(String message) { // 单消息版本
        Activity activity = getActivity();
        if (activity == null) {
            Log.w(TAG, "onProgressUpdate(String): Fragment not attached.");
            return;
        }
        activity.runOnUiThread(() -> {
            Log.d(TAG, "onProgressUpdate(String) (UI Thread). Message: " + message + ". Current Thread: " + Thread.currentThread().getName());
            if (loadingOverlayContainer != null && loadingOverlayContainer.getVisibility() == View.VISIBLE) {
                if (loadingStatusTextViewOverlay != null) {
                    loadingStatusTextViewOverlay.setText(message);
                } else {
                    Log.e(TAG, "onProgressUpdate(String): loadingStatusTextViewOverlay is null!");
                }
                if (loadingStepDetailsTextViewOverlay != null) {
                    loadingStepDetailsTextViewOverlay.setVisibility(View.GONE); // 单消息时隐藏详情
                }
            } else {
                Log.d(TAG, "onProgressUpdate(String): loadingOverlayContainer is null or not visible.");
            }
        });
    }

    @Override
    public void onProgressUpdate(String message, String details) { // 双消息版本
        Activity activity = getActivity();
        if (activity == null) {
            Log.w(TAG, "onProgressUpdate(String, String): Fragment not attached.");
            return;
        }
        activity.runOnUiThread(() -> {
            Log.d(TAG, "onProgressUpdate(String, String) (UI Thread). Message: " + message + ", Details: " + details + ". Current Thread: " + Thread.currentThread().getName());
            if (loadingOverlayContainer != null && loadingOverlayContainer.getVisibility() == View.VISIBLE) {
                if (loadingStatusTextViewOverlay != null) {
                    loadingStatusTextViewOverlay.setText(message);
                } else {
                    Log.e(TAG, "onProgressUpdate(String, String): loadingStatusTextViewOverlay is null!");
                }
                if (loadingStepDetailsTextViewOverlay != null) {
                    loadingStepDetailsTextViewOverlay.setText(details);
                    loadingStepDetailsTextViewOverlay.setVisibility(View.VISIBLE);
                } else {
                    Log.e(TAG, "onProgressUpdate(String, String): loadingStepDetailsTextViewOverlay is null!");
                }
            } else {
                Log.d(TAG, "onProgressUpdate(String, String): loadingOverlayContainer is null or not visible.");
            }
        });
    }

    @Override
    public void onProcessingComplete() {
        Activity activity = getActivity();
        if (activity == null) {
            Log.w(TAG, "onProcessingComplete: Fragment not attached.");
            return;
        }
        activity.runOnUiThread(() -> {
            Log.d(TAG, "onProcessingComplete (UI Thread)");
            if (loadingOverlayContainer != null) {
                loadingOverlayContainer.setVisibility(View.GONE);
                Log.d(TAG, "onProcessingComplete: loadingOverlayContainer set to GONE.");
            } else {
                Log.e(TAG, "onProcessingComplete: loadingOverlayContainer is null!");
            }
        });
    }

    @Override
    public void onProcessingError(String errorMessage) {
        Activity activity = getActivity();
        if (activity == null) {
            Log.w(TAG, "onProcessingError: Fragment not attached.");
            return;
        }
        activity.runOnUiThread(() -> {
            Log.e(TAG, "onProcessingError (UI Thread): " + errorMessage);
            if (loadingOverlayContainer != null) {
                loadingOverlayContainer.setVisibility(View.GONE);
            }
            if (getContext() != null) { // 确保上下文存在
                Toast.makeText(getContext(), "处理出错: " + errorMessage, Toast.LENGTH_LONG).show();
            }
        });
    }


    // 其他接口实现方法...
    @Override
    public void onChatGptResponse(String response) {
        Log.d(TAG, "ChatGptResponse: " + response);
        // 通常 GPT 响应处理在 DiabetesFoodAdvisor 内部，这里可能不需要做什么
    }

    @Override
    public void onError(String message) { // 这是 ChatGptHelper 的 onError
        Log.e(TAG, "ChatGptError: " + message);
        // 通常 GPT 错误处理在 DiabetesFoodAdvisor 内部，它会调用 onProcessingError
    }

    @Override
    public void AliyunAPIResponse(String response, int index) {
        if (imageRecognitionManager != null) {
            imageRecognitionManager.handleAliyunAPIResponse(response, index);
        }
    }

    @Override
    public void AliyunAPIError(String message) {
        Log.e(TAG, "AliyunAPIError: " + message);
        if (imageRecognitionManager != null) {
            imageRecognitionManager.handleAliyunAPIError(message);
            // Aliyun API 错误会通过 ImageRecognitionManager -> DiabetesFoodAdvisor -> onProcessingError
        }
        // 考虑是否直接在此处也调用 onProcessingError，以防调用链中断
        // onProcessingError("图像识别服务出错 (Aliyun): " + message);
    }

    @Override
    public void onDoubaoVisionResponse(String response, int index) {
        if (imageRecognitionManager != null) {
            imageRecognitionManager.handleDoubaoVisionResponse(response, index);
        }
    }

    @Override
    public void onDoubaoVisionError(String error, int index) {
        Log.e(TAG, "DoubaoVisionError: " + error + " for index " + index);
        if (imageRecognitionManager != null) {
            imageRecognitionManager.handleDoubaoVisionError(error, index);
        }
        // onProcessingError("图像识别服务出错 (Doubao): " + error);
    }


    @Override
    public void getFoodCaloriesResponse(String response) {
        Log.d(TAG, "FoodCaloriesResponse: " + response);
    }

    @Override
    public void getFoodDetailsResponse(String response) {
        Log.d(TAG, "FoodDetailsResponse: " + response);
    }

    @Override
    public void onMedicalAtlasResponse(String response) {
        Log.d(TAG, "MedicalAtlasResponse: " + response);
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
        // 可以考虑在这里检查 loadingOverlayContainer 的状态，例如如果app从后台回来时某个处理还在进行。
        // 但通常 LoadingProgressListener 的调用会处理UI更新。
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "onDestroyView");
        // 清理对UI组件的引用，防止内存泄漏
        loadingOverlayContainer = null;
        loadingStatusTextViewOverlay = null;
        loadingStepDetailsTextViewOverlay = null;
        // 如果 imageRecognitionManager 持有对 Fragment 的强引用，考虑在这里解除
        // if (imageRecognitionManager != null) {
        // imageRecognitionManager.setLoadingProgressListener(null); // 如果 ImageRecognitionManager 允许
        // }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
    }
}